package com.lry.basic.aop.core;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import org.junit.platform.commons.util.StringUtils;

import java.lang.reflect.Method;

/**
 * @author:刘仁有
 * @desc:
 * @email:953506233@qq.com
 * @data:2019/10/29
 */
public abstract class AbsMethodAdvance implements MethodInterceptor {
    private Object targetObject;

    private String proxyMethodName;

    public Object createProxyObject(Object target){
        this.targetObject = target;
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(this.targetObject.getClass());
        enhancer.setCallback(this);
        return enhancer.create();
    }

    @Override
    public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        if(StringUtils.isNotBlank(proxyMethodName) && proxyMethodName.equals(method.getName())){
            doBefore();
        }
        //执行拦截的方法
        Object result = methodProxy.invokeSuper(proxy,args);

        if(StringUtils.isNotBlank(proxyMethodName) && proxyMethodName.equals(method.getName())){
            doAfter();
        }
        return result;
    }

    public abstract void doBefore();

    public abstract void doAfter();

    public void setProxyMethodName(String proxyMethodName){
        this.proxyMethodName = proxyMethodName;
    }
}
